package com.wythe.mall.ui;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hb.dialog.myDialog.MyAlertDialog;
import com.wythe.mall.R;
import com.wythe.mall.activity.BuyActivity;
import com.wythe.mall.activity.LoginActivity;
import com.wythe.mall.adapter.CartListAdapter;
import com.wythe.mall.adapter.GoodsCartListAdapter;
import com.wythe.mall.intf.OnRequestDataListener;
import com.wythe.mall.model.CarBean;
import com.wythe.mall.model.ShopBean;
import com.wythe.mall.utils.ApiOkHttp;
import com.wythe.mall.utils.GotoActivity;
import com.wythe.mall.utils.SharePreferenceUtils;
import com.wythe.mall.utils.ToastUtil;
import com.wythe.mall.utils.UserManager;
import com.wythe.mall.view.CenterTextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;

public class CartFragment extends Fragment implements View.OnClickListener {

    private View view;
    private RecyclerView mainPullRefreshView;
    private GoodsCartListAdapter mainAdapter;
    private ArrayList<CarBean> mainArrayList;
    private ArrayList<CarBean> mSelectLists;
    private RelativeLayout tipsRelativeLayout;
    private AppCompatTextView tipsTextView;
    private AppCompatTextView balanceTextView;
    private AppCompatTextView moneyTextView;
    private CenterTextView mTopTitle;
    private AppCompatEditText mCountInfo;
    private ImageView mainCheckBox;
    private TextView mDelete;
    private LinearLayout operaLinearLayout;

    private double totalMoney = 0;
    private String mStrMoney = "0.00";
    private int totalCount = 0;
    private StringBuffer ids = new StringBuffer();
    private DecimalFormat format = new DecimalFormat("0.00");



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (mainArrayList == null) {
            mainArrayList = new ArrayList<>();
        }
        mainArrayList.clear();
        if (mSelectLists == null) {
            mSelectLists = new ArrayList<>();
        }
        mSelectLists.clear();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_cart, container, false);
        initView();
        return view;
    }

    private void initView() {
        ((TextView) view.findViewById(R.id.titleText)).setText(R.string.cart);
        view.findViewById(R.id.title_left_button).setVisibility(View.INVISIBLE);
        mTopTitle = view.findViewById(R.id.tv_top);
        operaLinearLayout = view.findViewById(R.id.operaLinearLayout);
        tipsRelativeLayout = view.findViewById(R.id.tipsRelativeLayout);
        mainPullRefreshView = view.findViewById(R.id.mainPullRefreshView);
        moneyTextView = view.findViewById(R.id.moneyTextView);

        mainCheckBox = view.findViewById(R.id.mainCheckBox);
        mDelete = view.findViewById(R.id.tv_manage);

        balanceTextView = view.findViewById(R.id.balanceTextView);
        tipsTextView = view.findViewById(R.id.tipsTextView);

    }

    public void initData() {
        moneyTextView.setText("");
        totalCount = 0;
        totalMoney = 0;

        mainCheckBox.setSelected(false);

        mDelete.setOnClickListener(this);
        mainCheckBox.setOnClickListener(this);
        balanceTextView.setOnClickListener(this);

        tipsRelativeLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!UserManager.getInstance().isLogin()) {
                    GotoActivity.gotoActiviy(getActivity(), LoginActivity.class);
                } else {
                    getCart();
                }
            }
        });
        if (UserManager.getInstance().isLogin()) {
            tipsRelativeLayout.setVisibility(View.GONE);
            mDelete.setVisibility(View.VISIBLE);
            mainPullRefreshView.setVisibility(View.VISIBLE);
            if (mainAdapter == null) {
                mainAdapter = new GoodsCartListAdapter(getActivity(), mainArrayList);
            }
            mainAdapter.setOnItemClickListener(new GoodsCartListAdapter.OnItemClickListener() {
                @Override
                public void onClick(int position, ImageView view) {
                    boolean selected = !view.isSelected();
                    view.setSelected(selected);
                    updateList(position, selected);
                }

                @Override
                public void onAddClick(int position, AppCompatEditText view) {
                    view.setEnabled(false);
                    CarBean carBean = mainArrayList.get(position);
                    int count = carBean.getCount();
                    if (count < carBean.getStockCount()) {
                        count = count + 1;
                        setModifyCount(count + "", carBean.getId(),view,position);

                    } else {
                        Toast.makeText(getActivity(), "库存不足", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onReduceClick(int position, AppCompatEditText view) {
                    view.setEnabled(false);
                    CarBean carBean = mainArrayList.get(position);
                    int count = carBean.getCount();
                    if (count > 1) {
                        count = count - 1;
                        setModifyCount(count + "", carBean.getId(),view,position);
                    } else {
                        Toast.makeText(getActivity(), "至少选择一件商品", Toast.LENGTH_SHORT).show();
                    }
                }
            });
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
            linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            mainPullRefreshView.setLayoutManager(linearLayoutManager);//设置布局管理器
            mainPullRefreshView.setAdapter(mainAdapter);

        } else {
            tipsRelativeLayout.setVisibility(View.VISIBLE);
            mainPullRefreshView.setVisibility(View.GONE);
            mTopTitle.setVisibility(View.GONE);
            mDelete.setVisibility(View.GONE);
        }

        if (UserManager.getInstance().isLogin()) {
            String stroeName = SharePreferenceUtils.getString(getActivity(), "store_name");
            mTopTitle.setText(stroeName);
            tipsTextView.setText("请稍后...");
            getCart();
        } else {
            tipsRelativeLayout.setVisibility(View.VISIBLE);
            mainPullRefreshView.setVisibility(View.GONE);
            mTopTitle.setVisibility(View.GONE);
            tipsTextView.setText("请登录...");
            mDelete.setVisibility(View.GONE);
        }
    }

    public void getCart() {
        JSONObject param = new JSONObject();

        ApiOkHttp.getCarList(getActivity(), param, new OnRequestDataListener() {
            @Override
            public void requestSuccess(int code, JSONObject data) {
                mainArrayList.clear();
                int resultCode = 0;
                JSONArray jsonArray = null;
                try {
                    resultCode = data.getInt("code");
                    if (resultCode == 10001 || resultCode == 10000) {
                        SharePreferenceUtils.putString(getActivity(), "KEY_TOKEN", "");
                        UserManager.getInstance().setLogin(false);
                        GotoActivity.gotoActiviy(getActivity(), LoginActivity.class);
                    } else {
                        jsonArray = data.getJSONArray("data");
                        for (int i = 0; i < jsonArray.length(); i++) {
                            CarBean bean = new Gson().fromJson(jsonArray.getJSONObject(i).toString(), CarBean.class);
                            mainArrayList.add(bean);
                        }
                        mainAdapter.setDatas(mainArrayList);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void requestFailure(int code, String msg) {

            }
        });
    }

    public void setModifyCount(final String count, int id, final AppCompatEditText view, final int position) {
        JSONObject param = new JSONObject();
        try {
            param.put("count", count);
            param.put("id", id);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        ApiOkHttp.setModifyCarCount(getActivity(), param, new OnRequestDataListener() {
            @Override
            public void requestSuccess(int code, JSONObject data) {

                try {
                    int code1 = data.getInt("code");
                    if (code1 == 200) {
                        view.setText(count);
                        mainArrayList.get(position).setCount(Integer.parseInt(count));
                        updateList(position,mainArrayList.get(position).isClick());
                    }

                    view.setEnabled(true);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void requestFailure(int code, String msg) {

            }
        });
    }

    public void deleteCarCount() {
        JSONObject param = new JSONObject();
        try {
            String regex = "^,*|,*$";
            String str1 = ids.toString().trim().replaceAll(regex, "");
            param.put("id", str1);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ApiOkHttp.deletCarCount(getActivity(), param, new OnRequestDataListener() {
            @Override
            public void requestSuccess(int code, JSONObject data) {
                try {
                    mainArrayList.clear();
                    JSONArray jsonArray = data.getJSONArray("data");
                    for (int i = 0; i < jsonArray.length(); i++) {
                        CarBean bean = new Gson().fromJson(jsonArray.getJSONObject(i).toString(), CarBean.class);
                        mainArrayList.add(bean);
                    }
                    mainAdapter.setDatas(mainArrayList);
                    totalMoney = 0;
                    totalCount = 0;
                    mStrMoney = "0.00";
                    ids.setLength(0);
                    String msg = data.getString("msg");
                    ToastUtil.show(getActivity(),msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void requestFailure(int code, String msg) {

            }
        });
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }

    private void updateList(int position, boolean isSelect) {
        mainArrayList.get(position).setClick(isSelect);
        totalMoney = 0;
        totalCount = 0;
        mStrMoney = "0.00";
        ids.setLength(0);
        mSelectLists.clear();
        for (CarBean carBean : mainArrayList) {
            if (carBean.isClick()) {
                totalMoney = carBean.getCount() * carBean.getPrice() + totalMoney;
                mStrMoney = format.format(totalMoney);
                totalCount++;
                ids.append(carBean.getId() + ",");
                mSelectLists.add(carBean);
            }
        }

        if (totalCount == mainArrayList.size()) {
            mainCheckBox.setSelected(true);
        } else {
            mainCheckBox.setSelected(false);
        }
        String content = "合计： 共计<font color=\"#FF0000\">" + totalCount + "</font>件  "+"<font color=\"#FF0000\">￥" + mStrMoney + "</font>";
        moneyTextView.setText(Html.fromHtml(content));
        mainAdapter.notifyDataSetChanged();
    }

    private void updateAllList(boolean isSelect) {
        totalMoney = 0;
        totalCount = 0;
        mStrMoney = "0.00";
        ids.setLength(0);
        mSelectLists.clear();
        if (isSelect) {
            for (int i = 0; i < mainArrayList.size(); i++) {
                mainArrayList.get(i).setClick(true);
                totalMoney = mainArrayList.get(i).getCount() * mainArrayList.get(i).getPrice() + totalMoney;
                mStrMoney = format.format(totalMoney);
                totalCount++;
                ids.append(mainArrayList.get(i).getId() + ",");
                mSelectLists.add(mainArrayList.get(i));
            }
        } else {
            for (int i = 0; i < mainArrayList.size(); i++) {
                mainArrayList.get(i).setClick(false);
            }
        }

        String content = "合计： 共计<font color=\"#FF0000\">" + totalCount + "</font>件  "+"<font color=\"#FF0000\">￥" + mStrMoney + "</font>";
        moneyTextView.setText(Html.fromHtml(content));

        mainAdapter.notifyDataSetChanged();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_left_button: {
                Toast.makeText(getActivity(), "去哪儿？", Toast.LENGTH_LONG).show();
                break;
            }
            case R.id.mainCheckBox:
                if (UserManager.getInstance().isLogin()) {
                    boolean selected = !mainCheckBox.isSelected();
                    v.setSelected(selected);
                    updateAllList(selected);
                }
                break;

            case R.id.tv_manage:
                if ("管理".equals(mDelete.getText())) {
                    mDelete.setText("完成");
                    balanceTextView.setText("删除");
                    moneyTextView.setVisibility(View.INVISIBLE);
                } else if ("完成".equals(mDelete.getText())) {
                    mDelete.setText("管理");
                    balanceTextView.setText("结算");
                    moneyTextView.setVisibility(View.VISIBLE);
                }
                String content = "合计： 共计<font color=\"#FF0000\">" + totalCount + "</font>件  "+"<font color=\"#FF0000\">￥" + mStrMoney + "</font>";
                moneyTextView.setText(Html.fromHtml(content));
                break;
            case R.id.balanceTextView:
                CharSequence text = balanceTextView.getText();
                if ("结算".equals(text)) {
                    if (totalCount > 0) {
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("list",mSelectLists);
                        bundle.putDouble("money",totalMoney);
                        bundle.putInt("count",totalCount);
                        GotoActivity.gotoActiviy(getActivity(), BuyActivity.class,bundle);
                    } else {
                        ToastUtil.show(getActivity(),"未选择结算商品");
                    }
                } else if ("删除".equals(text)) {
                    if (totalCount > 0) {
                        MyAlertDialog myAlertDialog = new MyAlertDialog(getActivity());
                        myAlertDialog.builder();
                        myAlertDialog.setTitle("温馨提示");
                        myAlertDialog.setMsg("你确定将购物车商品删除？");
                        myAlertDialog.setPositiveButton("确认", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                deleteCarCount();
                            }
                        });
                        myAlertDialog.setNegativeButton("取消", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                            }
                        });
                        myAlertDialog.show();
                    } else {
                        ToastUtil.show(getActivity(),"未选择删除商品");
                    }
                }
                break;
            default:
                break;
        }
    }
}
